package com.ssyc.student.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.GrammarDetectionInfo;
import com.ssyc.student.fragment.StudentGrammarCommitFragment;
import com.ssyc.student.fragment.StudentGrammarConjunctionsFragment;
import com.ssyc.student.fragment.StudentGrammarSingleChooseFragment;
import com.ssyc.student.fragment.StudentGrammarTranslateFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--语法检测界面
 * Created by Kevin on 2018/5/29
 */

public class StudentGrammarDetectionActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //返回按钮
    private ImageView ivBack;

    //底部的ViewPager
    private SuperViewPager vp;

    //底部的显示Vp页数的文本
    private TextView tvPos;

    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;

    //Handler对象
    private Handler handler = new Handler();

    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;

    //进度条
    private ZzHorizontalProgressBar pb;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    //记录用户保存的时间
    public static long firstTime;

    //查看答案的消息标记
    public static final int LOOKANSWER = 0x180;

    //是否提交
    public static int isCommit = -1;

    //时间rowid
    private String rowId;

    //精力值
    private String energy;

    //静态代码块
    {
        //这里使用有序的Map来存放题目
        chooseAnswerMap = new LinkedHashMap<>();
        answerMap = new LinkedHashMap<>();

        //记录用户第一次进入的时间
        firstTime = System.currentTimeMillis();

        //初始化计时器
        TimeCount.init();
    }

    //获取保存答题Map的方法
    public static Map<Integer, String> getChooseAnswerMap() {
        return chooseAnswerMap;
    }

    //获取保存答题正确或者错误Map的方法
    public static Map<Integer, Boolean> getAnswerMap() {
        return answerMap;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_grammar_detection;
    }

    @Override
    protected void init() {

        //初始化View
        initView();

        //获取传递过来的对象
        initIntent();

        //请求服务器
        http();
    }

    /**
     * 提供获取第一次进入时间的方法
     *
     * @return
     */
    public static long getFirstTime() {
        return firstTime;
    }

    /**
     * 初始化控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        tvPos = findViewById(R.id.tv_vp_pos);
        vp.addOnPageChangeListener(this);
        pb = findViewById(R.id.pb);
    }

    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }

    /**
     * 亮屏进入
     */
    @Override
    protected void onResume() {
        super.onResume();
        if(isCommit==-1){

        RecordTimeUtil.httpEnterTime(this,lessonId,gradeId,"14", new RecordTimeUtil.onRecordRowIdListener() {
            @Override
            public void recordRowId(String id,String en) {

                rowId = id;
                energy = en;
            }
        });
        }
    }

    /**
     * 息屏结束计时
     */
    @Override
    protected void onPause() {
        super.onPause();
        if(isCommit==-1) {
            RecordTimeUtil.httpExitTime(rowId, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isCommit = -1;
    }

    /**
     * 请求服务器
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "21");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "14");
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.GRAMMAR, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                GrammarDetectionInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, GrammarDetectionInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }

                Log.i("test", response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        //初始化Fragments
                        initFragments(info);

                        //初始化Vp的操作
                        initVp();
                    } else {
                        Log.i("test", info.getState());
                    }
                }
            }
        });
    }


    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(GrammarDetectionInfo info) {

        mFragments = new ArrayList<>();
        //连词成句
        for (int i = 0; i < info.getData().getQuestion_list().getConjunction().size(); i++) {
            mFragments.add(StudentGrammarConjunctionsFragment.newInstance(GsonUtil.objectToJson(info.getData().getQuestion_list()), i));
        }

        //翻译
        for (int i = 0; i < info.getData().getQuestion_list().getTranslation().size(); i++) {
            mFragments.add(StudentGrammarTranslateFragment.newInstance(GsonUtil.objectToJson(info.getData().getQuestion_list()), i));
        }

        //单选
        for (int i = 0; i < info.getData().getQuestion_list().getRadio().size(); i++) {
            mFragments.add(StudentGrammarSingleChooseFragment.newInstance(GsonUtil.objectToJson(info.getData().getQuestion_list()), i));
        }

        //添加最后一个提交页面的Fragment
        mFragments.add(StudentGrammarCommitFragment.newInstance(GsonUtil.objectToJson(info), lessonId, gradeId));

        //设置当前展示的Vp的页码
        tvPos.setText("1/" + (mFragments.size() - 1));

        //设置默认进度条的值
        pb.setProgress((int) ((float) (1) / (float) (mFragments.size() - 1) * 100));

        for (int i = 0; i < info.getData().getQuestion_list().getConjunction().size() +
                info.getData().getQuestion_list().getTranslation().size() +
                info.getData().getQuestion_list().getRadio().size()
                ; i++) {
            StudentGrammarDetectionActivity.getChooseAnswerMap().put(i, "");
            getAnswerMap().put(i, false);
        }
    }


    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
        if (position != mFragments.size() - 1) {
            tvPos.setVisibility(View.VISIBLE);
            tvPos.setText((position + 1) + "/" + (mFragments.size() - 1));
        } else {
            tvPos.setVisibility(View.GONE);
        }
//        //记录当前滑动位置
//        currPos = position;
//        //复制vp滑动的最大位置值
//        if (position > maxPos) {
//            maxPos = position;
//        }
//        //根据当前位置来设置Vp是否可以向右滑动
//        if (currPos < maxPos) {
//            //如果当前位置小于Vp滑动过的最大位置,则可以右滑,否则不能右滑
//            vp.setScrollble(true);
//        } else {
//            vp.setScrollble(false);
//        }

        //最后一个位置不进行设置
        if (position != mFragments.size() - 1) {
            //设置进度条的文本显示值
            tvPos.setText((position + 1) + "/" + (mFragments.size() - 1));

            //同时需要设置进度条的值
            pb.setProgress((int) ((float) (pos + 1) / (float) (mFragments.size() - 1) * 100));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //通知ViewPager翻页
        if (null != busInfo && StudentGrammarConjunctionsFragment.VPSCOLL.equals(busInfo.vpScoll)) {
            pos += 1;

            //延迟800毫秒跳转页面
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    vp.setCurrentItem(pos);
                }
            }, 0);
        } else if (busInfo != null && StudentGrammarDetectionActivity.LOOKANSWER == busInfo.getType()) {
            if(isCommit==-1) {
                RecordTimeUtil.httpExitTime(rowId, this);
            }
            isCommit = 1;
            vp.setCurrentItem(0);
        }else if (busInfo != null && StudentGrammarCommitFragment.JUMPFRAGMENT == busInfo.getType()) {

            int pos = busInfo.getPos();
            vp.setCurrentItem(pos);
        }
    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //关闭
            finish();
        }
    }
}
